package com.wafer.server;

import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.wafer.server.config.PackagePathConfig;
import com.wafer.server.listener.WaferServerInitListener;
import com.wafer.server.util.PackageUtil;

/**
 * 用于初始化定义的所有监听器并调用对应监听器的对应方法, 监听器用于启动Socket前或之后用于数据初始化工作
 * 
 * @date 2018-07-29
 * @author wanbo
 *
 */
public class ListenerHandler {
	
	private static final Logger logger = Logger.getLogger(ListenerHandler.class);
	
	/**
	 *  map 用来记录所有实例化的listener, key为监听器名称
	 */
	private static Hashtable<String, Object> listenersInstancesMap = new Hashtable<String, Object>();
	
	/**
	 * List 用来记录所有实例化的listener, 由于是启动过程的加载，所以不涉及线程安全问题。
	 */
	private static List<WaferServerInitListener> listenerInstancesList = new LinkedList<WaferServerInitListener>();

	
	
	public ListenerHandler() {
		
		List<String> listenerClassNames = PackageUtil.getClassName(PackagePathConfig.Listener_Implemention_Path);
		List<String> listenerClassNames2 = new LinkedList<String>();
		for(String listener:listenerClassNames) {
			listenerClassNames2.add(listener.replaceAll(".class$", ""));
		}
		logger.debug("listenerClassNames:" + JSON.toJSONString(listenerClassNames2));
		instanceListener(listenerClassNames2);
	}
	
	
	/**
	 * @todo  实例化监听器
	 * @param listenerClassNames  监听器限制名称
	 */
	private void instanceListener(List<String> listenerClassNames) {
		
	    for(String name:listenerClassNames) {
	    	try {
				   Class<?> clazz = Class.forName(PackagePathConfig.Listener_Implemention_Path + "." + name);
				   Object o = clazz.newInstance();	
				   if(o instanceof WaferServerInitListener) {
					   listenersInstancesMap.put(name, o);
					   listenerInstancesList.add((WaferServerInitListener)o);
				   }else {
					   logger.error(name + " Error Listener");
				   }

			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
	    }
	}
	
	/**
	 * 调用实例化过的Listener方法
	 */
	public void invokeListenerMethod() {
		if(listenerInstancesList.size() > 0) {
			// 先对监听器进行排序
			Collections.sort(listenerInstancesList, new Comparator<WaferServerInitListener>() {

				public int compare(WaferServerInitListener o1, WaferServerInitListener o2) {
					
					if(o1 == null) {  // 未定义返回默认顺序 ( 其实o1不可能为null )
						return 5;
					}
					if(o2 == null) {
						return 5;
					}
					return o1.getListenerInitOrder() - o2.getListenerInitOrder();
				}
				
			});
			
		}else {
			logger.info(" Listener num <= 0 ");
		}
		
		// 遍历监听器， 最终执行监听器的方法
		for(WaferServerInitListener listener:listenerInstancesList) {
			listener.doListenWork();
			logger.info(String.format("Listener Order=%s Is Working", listener.getListenerInitOrder() ));
		}
		
	}
	

}

















